<template>
  <view class="reservation-list-page">
    <!-- 导航栏 -->
    <u-navbar 
      title="我的预约" 
      :border="true"
      left-icon="arrow-left"
      @leftClick="goBack"
    />
    
    <!-- 状态筛选 -->
    <view class="filter-section">
      <scroll-view scroll-x class="status-filter">
        <view class="filter-items">
          <view 
            v-for="status in statusOptions" 
            :key="status.value"
            class="filter-item"
            :class="{ active: currentStatus === status.value }"
            @tap="filterByStatus(status.value)"
          >
            <text class="filter-text">{{ status.label }}</text>
            <view v-if="status.count > 0" class="filter-badge">{{ status.count }}</view>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 预约列表 -->
    <view class="reservation-list">
      <view v-if="loading" class="loading-container">
        <u-loading-icon mode="circle"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else-if="reservations.length === 0" class="empty-container">
        <u-empty 
          mode="list" 
          text="暂无预约记录"
          textColor="#c0c4cc"
          iconSize="120"
        >
          <template #bottom>
            <u-button 
              type="primary" 
              size="small"
              @click="goToUpload"
            >
              上传文件
            </u-button>
          </template>
        </u-empty>
      </view>
      
      <view v-else>
        <view 
          v-for="reservation in reservations" 
          :key="reservation.id"
          class="reservation-item"
          @tap="viewReservation(reservation)"
        >
          <!-- 预约状态 -->
          <view class="reservation-header">
            <view class="status-badge" :class="[getStatusClass(reservation.status)]">
              <text class="status-text">{{ getStatusText(reservation.status) }}</text>
            </view>
            <text class="reservation-time">{{ formatTime(reservation.reservedAt) }}</text>
          </view>
          
          <!-- 文件信息 -->
          <view class="file-info">
            <view class="file-icon">
              <u-icon :name="getFileIcon(reservation.file.file_type)" size="20" color="#409eff"></u-icon>
            </view>
            <view class="file-details">
              <text class="file-name">{{ reservation.file.original_name }}</text>
              <text class="file-meta">{{ formatFileSize(reservation.file.file_size) }} · {{ reservation.file.page_count || 1 }}页</text>
            </view>
          </view>
          
          <!-- 打印信息 -->
          <view class="print-info">
            <view class="print-item">
              <text class="print-label">预约码</text>
              <text class="print-value">{{ reservation.reservationCode }}</text>
            </view>
            <view class="print-item">
              <text class="print-label">打印份数</text>
              <text class="print-value">{{ reservation.quantity }}份</text>
            </view>
            <view class="print-item">
              <text class="print-label">消费积分</text>
              <text class="print-value highlight">{{ reservation.pointsCost }}积分</text>
            </view>
          </view>
          
          <!-- 过期提醒 -->
          <view v-if="isExpiringSoon(reservation)" class="expiry-warning">
            <u-icon name="warning" size="14" color="#f56c6c"></u-icon>
            <text class="warning-text">即将过期，请尽快到店打印</text>
          </view>
          
          <!-- 操作按钮 -->
          <view class="reservation-actions">
            <u-button 
              v-if="canCancel(reservation)"
              type="error" 
              size="mini"
              @click.stop="cancelReservation(reservation)"
            >
              取消
            </u-button>
            <u-button 
              type="primary" 
              size="mini"
              @click.stop="viewReservation(reservation)"
            >
              查看详情
            </u-button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="hasMore && !loading" class="load-more" @tap="loadMore">
      <text>加载更多</text>
    </view>
    
    <!-- 取消确认弹窗 -->
    <u-modal 
      :show="showCancelModal"
      title="取消预约"
      content="确定要取消这个预约吗？取消后积分将退还到您的账户。"
      @confirm="confirmCancel"
      @cancel="showCancelModal = false"
    />
  </view>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'ReservationList',
  data() {
    return {
      reservations: [],
      loading: false,
      currentStatus: null,
      currentPage: 1,
      pageSize: 20,
      hasMore: true,
      showCancelModal: false,
      selectedReservation: null,
      statusOptions: [
        { label: '全部', value: null, count: 0 },
        { label: '等待确认', value: 'pending', count: 0 },
        { label: '已确认', value: 'confirmed', count: 0 },
        { label: '打印中', value: 'processing', count: 0 },
        { label: '已完成', value: 'completed', count: 0 },
        { label: '已取消', value: 'cancelled', count: 0 },
        { label: '已过期', value: 'expired', count: 0 }
      ]
    }
  },
  
  computed: {
    ...mapState('user', ['userInfo'])
  },
  
  onLoad() {
    this.loadReservations()
  },
  
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  
  onPullDownRefresh() {
    this.refreshReservations()
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 加载预约列表
    async loadReservations(reset = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const page = reset ? 1 : this.currentPage
        const response = await this.$http.get('/api/print/reservations', {
          params: {
            page,
            limit: this.pageSize,
            status: this.currentStatus
          }
        })
        
        if (response.data.success) {
          const { reservations, pagination } = response.data.data
          
          if (reset) {
            this.reservations = reservations
            this.currentPage = 1
          } else {
            this.reservations = [...this.reservations, ...reservations]
          }
          
          this.hasMore = pagination.page < pagination.pages
          this.currentPage = pagination.page
          
          // 更新状态计数
          this.updateStatusCounts()
        }
      } catch (error) {
        console.error('加载预约列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        if (reset) {
          uni.stopPullDownRefresh()
        }
      }
    },
    
    // 刷新预约列表
    refreshReservations() {
      this.loadReservations(true)
    },
    
    // 加载更多
    loadMore() {
      this.currentPage++
      this.loadReservations()
    },
    
    // 按状态筛选
    filterByStatus(status) {
      if (this.currentStatus === status) return
      
      this.currentStatus = status
      this.currentPage = 1
      this.hasMore = true
      this.loadReservations(true)
    },
    
    // 更新状态计数
    updateStatusCounts() {
      // 这里可以调用API获取各状态的数量
      // 暂时使用本地计算
      const statusCounts = {}
      this.reservations.forEach(reservation => {
        statusCounts[reservation.status] = (statusCounts[reservation.status] || 0) + 1
      })
      
      this.statusOptions.forEach(option => {
        if (option.value) {
          option.count = statusCounts[option.value] || 0
        } else {
          option.count = this.reservations.length
        }
      })
    },
    
    // 查看预约详情
    viewReservation(reservation) {
      uni.navigateTo({
        url: `/pages/print/reservation?id=${reservation.id}`
      })
    },
    
    // 取消预约
    cancelReservation(reservation) {
      this.selectedReservation = reservation
      this.showCancelModal = true
    },
    
    // 确认取消预约
    async confirmCancel() {
      this.showCancelModal = false
      
      if (!this.selectedReservation) return
      
      try {
        uni.showLoading({ title: '取消中...' })
        
        const response = await this.$http.post(`/api/print/reservations/${this.selectedReservation.id}/cancel`)
        
        if (response.data.success) {
          uni.showToast({
            title: '预约已取消',
            icon: 'success'
          })
          
          // 刷新列表
          this.refreshReservations()
        }
      } catch (error) {
        console.error('取消预约失败:', error)
        uni.showToast({
          title: (error.response && error.response.data && error.response.data.message) || '取消失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
        this.selectedReservation = null
      }
    },
    
    // 跳转到文件上传
    goToUpload() {
      uni.navigateTo({
        url: '/pages/files/upload'
      })
    },
    
    // 判断是否可以取消
    canCancel(reservation) {
      return ['pending', 'confirmed'].includes(reservation.status)
    },
    
    // 判断是否即将过期
    isExpiringSoon(reservation) {
      if (reservation.status !== 'pending') return false
      
      const now = new Date()
      const expiresAt = new Date(reservation.expiresAt)
      const timeDiff = expiresAt - now
      
      // 2小时内过期
      return timeDiff > 0 && timeDiff < 2 * 60 * 60 * 1000
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        'pending': 'status-pending',
        'confirmed': 'status-confirmed',
        'processing': 'status-processing',
        'completed': 'status-completed',
        'cancelled': 'status-cancelled',
        'expired': 'status-expired'
      }
      return classMap[status] || 'status-pending'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        'pending': '等待确认',
        'confirmed': '已确认',
        'processing': '打印中',
        'completed': '已完成',
        'cancelled': '已取消',
        'expired': '已过期'
      }
      return textMap[status] || status
    },
    
    // 获取文件图标
    getFileIcon(fileType) {
      if (!fileType) return 'file-text'
      
      if (fileType.includes('pdf')) return 'file-pdf'
      if (fileType.includes('word') || fileType.includes('document')) return 'file-word'
      if (fileType.includes('excel') || fileType.includes('sheet')) return 'file-excel'
      if (fileType.includes('powerpoint') || fileType.includes('presentation')) return 'file-ppt'
      if (fileType.includes('image')) return 'image'
      if (fileType.includes('text')) return 'file-text'
      
      return 'file'
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    // 格式化时间
    formatTime(dateString) {
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
      if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
      if (diff < 604800000) return Math.floor(diff / 86400000) + '天前'
      
      return date.toLocaleDateString()
    }
  }
}
</script>

<style lang="scss" scoped>
.reservation-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.filter-section {
  background: white;
  padding: 20rpx 0;
  
  .status-filter {
    white-space: nowrap;
    
    .filter-items {
      display: flex;
      padding: 0 20rpx;
      
      .filter-item {
        position: relative;
        padding: 16rpx 24rpx;
        margin-right: 20rpx;
        background: #f8f9fa;
        border-radius: 20rpx;
        border: 2rpx solid transparent;
        
        &.active {
          background: #e7f4ff;
          border-color: #409eff;
          
          .filter-text {
            color: #409eff;
            font-weight: 500;
          }
        }
        
        .filter-text {
          font-size: 28rpx;
          color: #606266;
          white-space: nowrap;
        }
        
        .filter-badge {
          position: absolute;
          top: -8rpx;
          right: -8rpx;
          background: #f56c6c;
          color: white;
          font-size: 20rpx;
          padding: 4rpx 8rpx;
          border-radius: 10rpx;
          line-height: 1;
          min-width: 32rpx;
          text-align: center;
        }
      }
    }
  }
}

.reservation-list {
  padding: 20rpx;
}

.loading-container, .empty-container {
  padding: 80rpx 40rpx;
  text-align: center;
  
  .loading-text {
    display: block;
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #909399;
  }
}

.reservation-item {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  &:active {
    background-color: #f8f9fa;
  }
  
  .reservation-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .status-badge {
      padding: 8rpx 16rpx;
      border-radius: 12rpx;
      
      &.status-pending {
        background: #fff3e0;
        
        .status-text {
          color: #ff9800;
        }
      }
      
      &.status-confirmed {
        background: #e3f2fd;
        
        .status-text {
          color: #2196f3;
        }
      }
      
      &.status-processing {
        background: #f3e5f5;
        
        .status-text {
          color: #9c27b0;
        }
      }
      
      &.status-completed {
        background: #e8f5e8;
        
        .status-text {
          color: #4caf50;
        }
      }
      
      &.status-cancelled, &.status-expired {
        background: #ffebee;
        
        .status-text {
          color: #f44336;
        }
      }
      
      .status-text {
        font-size: 24rpx;
        font-weight: 500;
      }
    }
    
    .reservation-time {
      font-size: 26rpx;
      color: #909399;
    }
  }
  
  .file-info {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .file-icon {
      margin-right: 16rpx;
    }
    
    .file-details {
      flex: 1;
      
      .file-name {
        display: block;
        font-size: 30rpx;
        color: #303133;
        font-weight: 500;
        margin-bottom: 8rpx;
      }
      
      .file-meta {
        font-size: 26rpx;
        color: #909399;
      }
    }
  }
  
  .print-info {
    margin-bottom: 20rpx;
    
    .print-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .print-label {
        font-size: 28rpx;
        color: #606266;
      }
      
      .print-value {
        font-size: 28rpx;
        color: #303133;
        
        &.highlight {
          color: #409eff;
          font-weight: 500;
        }
      }
    }
  }
  
  .expiry-warning {
    display: flex;
    align-items: center;
    padding: 12rpx 16rpx;
    background: #fff2f0;
    border-radius: 8rpx;
    margin-bottom: 20rpx;
    
    .warning-text {
      margin-left: 8rpx;
      font-size: 26rpx;
      color: #f56c6c;
    }
  }
  
  .reservation-actions {
    display: flex;
    justify-content: flex-end;
    gap: 16rpx;
  }
}

.load-more {
  text-align: center;
  padding: 40rpx;
  
  text {
    font-size: 28rpx;
    color: #409eff;
  }
}
</style>